<?php
/**
 * Groups Model. Provides an API for groups management
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Usermanagement Module
 * @subpackage Model
 * @license  New BSD License
 *
 */
class Models_Usermanagement_Groups extends Bel_Model_Abstract {
	
	/**
	 * Array of names of table classes which have one-to-many relations with groups' table
	 *
	 * @var array
	 */	
	protected $_dependentTables = array ('Models_Usermanagement_Users','Models_Usermanagement_Permissions');
	
	/**
	 * Constructor. Sets table name & primary key
	 *
	 * @param array $array - see Zend_Db_Table_Abstract for details
	 */	
	public function __construct($array = array()) {
		$this->_name = TABLE_PREFIX . 'user_groups';
		$this->_primary = array ('user_group_id' );
		parent::__construct ( $array );
	}
	
	/**
	 * Sets guest_type flag into 0
	 *
	 */
	public function resetGuestGroup() {
		$this->update ( array ('is_guest' => '0' ),NULL );
	}
	
	/**
	 * Sets default type flag into 0
	 *
	 */
	public function resetDefaultGroup() {
		$this->update ( array ('is_default' => '0' ),NULL );
	}
	
	
	/**
	 * Return default group data
	 *
	 * @return array
	 */
	public function getDefaultGroup() {
		$row = $this->fetchRow ( 'is_default = 1' );
		if ($row) {
			$row_array = $row->toArray ();
			return $row_array ['user_group_id'];
		} else
			return false;
	}
	
	/**
	 * Returns guest group data
	 *
	 * @return array
	 */
	public function getGuestsGroup() {
		$row = $this->fetchRow ( 'is_guest = 1' );
		if ($row) {
			$row_array = $row->toArray ();
			return $row_array ['user_group_id'];
		} else
			return false;
	}
	
	/**
	 * Returns group of the current site visitor
	 *
	 * @return int
	 */
	public function getCurrentGroupId() {
		$this->_session = new Zend_Session_Namespace ( 'auth' );
		if ($this->_session->userdata) {
			$userdata = $this->_session->userdata->user_group_id;
			$group_id = (isset ( $userdata )) ? $userdata : $this->getGuestsGroup ();
		} else {
			$group_id = $this->getGuestsGroup ();
		}
		return $group_id;
	}
}